import opendap.dap.*;

import java.util.Enumeration;
import java.util.Scanner;
import java.io.*;
import java.util.regex.*;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import opendap.util.geturl.gui.*;

public class GridDataDap {

	public static void main(String[] args)
	{

		String url = "http://test.opendap.org/dap/data/nc/sst.mnmean.nc.gz";
		String time = "[0]";
		String lat = "[13:18]";
		String lon = "[103:108]";
		String constraintExp = "sst"+time+lat+lon;
		String outFile = "myData.csv";
		GetData( url, constraintExp, outFile);
		
		
	}
	
	public static void GetData(String url, String constraintExp, String outFile)
	{
//		http://test.opendap.org/dap/data/nc/sst.mnmean.nc.gz
		
		String fileName = "temp.txt";
		
		try{
			//Scanner input = new Scanner(System.in);
			
		//	System.out.print("Enter Data URL:");
		//	String url = input.nextLine();
		//	String url = "http://test.opendap.org/dap/data/nc/sst.mnmean.nc.gz";
			
			DConnect2 dc = new DConnect2(url);
			
	
			
			
			System.out.println("");
	        System.out.println("");
	        System.out.println("########################################################");
	        System.out.println("\nConnecting to " + url + "\n");
	
	

	        System.out.println("\n- - - - - - - - - - - - - - - - - - -");
	
	        
	        
	        System.out.println("Retrieving DDS:\n");
	        DDS dds = dc.getDDS();
	        dds.print(System.out);
		    
	        
	        System.out.println("\n- - - - - - - - - - - - - - - - - - -");
	        System.out.println("Retrieving DATA:\n");
	        dds = dc.getData(constraintExp);
	      //  dds = dc.getData("",sw);
	        //write the data to a consol
	        dds.printVal(System.out, "", false);
	        System.out.println("\n");
	        // write the data only to a file
	        dds.printVal(new PrintStream(new File(fileName)), "", false);	        	
	        
	        
	        String Temp = readInput(fileName);  
	        
	        //Break Up Major String into Map And Array of data
	        String[] splitString = (Temp.split("MAPS: "));
	        String Map = splitString[1];
	        String Array = splitString[0];
	        
	        //Breakup the Map into parts that will work for its three components
	        String regex_ = "}, \\{";
	        String[] MapSplit = Map.split(regex_);
	        
            //Get the Map Variables Brute Force. Not Pretty
            String Time = ScrubString(MapSplit[0]);
            String[]Times = Time.split(", ");
            String Lat = ScrubString(MapSplit[1]);
            String[]Lats = Lat.split(", ");
            String Lon = ScrubString(MapSplit[2]);
            String[]Lons = Lon.split(", ");
            
            
            //Breakup the data into array elements
            String[] ArraySplit = Array.split("\\}\\},\\{\\{");
            
	        
	        
	       //Print out object 
	        try {
	       // declare a print stream object
	       // Create a new file output stream
	         
	        FileOutputStream out= new FileOutputStream(outFile); 
	       
	        // Connect print stream to the output stream
	        PrintStream ps = new PrintStream(out);
	        
	        //Print Key
	        ps.println("Key");
	        ps.println("URL:, "+ url);
	        ps.println("Constrain Expression:, "+ constraintExp);
	        // ps.println("Time: " + time);
	      //  ps.println("Lat: " + lat);
	      //  ps.println("Lon: " + lon);
	        ps.println("");
	        
	        //Print the following data
	        //Print out the header that defines the map
	        ps.println("MAPS");
	        ps.println("Time(s):, " + Time);
	        ps.println("Lat(s):, " + Lat);
	        ps.println("Lon(s):, " + Lon);
	        ps.println("");
	        ps.println("Array Data");
	        //Print out the body of the data
	        //System.out.println("\n\nArray" + Array +"\n");
	        
	        //this data goes into the csv
	        int i = 0;
	        for (String s : ArraySplit) {
	            
	        	ps.println(" - Time "+Times[i]+  " -");
	        	ps.println("Lon ->, "+Lon);
	        	
	        	
	        	String[] elementSplit = s.split("\\},\\{");
	        	int j =0;
	        	for (String element : elementSplit){
	        		ps.println("Lat:"+Lats[j]+", "+ ScrubString(element));
	        		j++;
	        	}
	        	i++;
	        	ps.println("\n");
	        //	System.out.println(s + "\n");
	        }
	        
	        
	        System.err.println ("Write successfully");
	        JOptionPane.showMessageDialog(new JFrame(),  "Output file " + outFile + " successfully written.", "Output file written", JOptionPane.INFORMATION_MESSAGE);
	        ps.close();
	        }
	        catch (Exception e){
	        System.err.println ("Error in writing to file");
	        }
	       
            
	       
	        
	        
			//input.close();
		}
		catch(Throwable t) {
            t.printStackTrace(System.err);	
		}	
	}

	static String readInput(String fileName) {
	    StringBuffer buffer = new StringBuffer();
	    try {
	        FileInputStream fis = new FileInputStream(fileName);
	        InputStreamReader isr = new InputStreamReader(fis, "UTF8");
	        Reader in = new BufferedReader(isr);
	        int ch;
	        while ((ch = in.read()) > -1) {
	            buffer.append((char)ch);
	        }
	        in.close();
	        return buffer.toString();
	    } 
	    catch (IOException e) {
	        e.printStackTrace();
	        return null;
	    }
	}
	
	static String ScrubString(String dirtyString){
		
		return dirtyString.replaceAll("\\{", "").replaceAll("\\}", "").replaceAll("  ARRAY: ", "");
	}
}
